package com.gezi.admin.module.code.tmpl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gezi.admin.config.exception.type.ApiException;
import com.gezi.admin.module.code.tmpl.model.CodeTmplAddParamModel;
import com.gezi.admin.module.code.tmpl.model.CodeTmplEditParamModel;
import com.gezi.admin.module.code.tmpl.model.CodeTmplSearchModel;
import com.gezi.admin.module.config.BaseController;
import com.gezi.admin.module.config.utils.PageUtil;
import com.gezi.admin.module.config.utils.PageVo;
import com.gezi.admin.utils.BeanValidators;
import com.gezi.admin.utils.excel.GzExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;


/**
 * 测试模板
 *
 * @Author 格子软件
 * @createDate 2024/2/10 09:00
 * @contact 公众号：格子软件 微信：13716343106 邮箱：1424529270@qq.com
 **/
@Slf4j
@Api(tags = "测试模板")
@RestController
@RequestMapping("api/code/tmpl")
public class CodeTmplController extends BaseController {

    @Resource
    private CodeTmplService codeTmplService;

    @ApiOperation("查询分页")
    @GetMapping(value = "/findAllByPage")
    public Object findAllByPage(PageVo page, CodeTmplSearchModel searchVo) {
        Page<Map> pageData = codeTmplService.findByPage(PageUtil.initMpPage(page), searchVo);
        return pageData;
    }

    @ApiOperation("查询列表")
    @GetMapping(value = "/findAllByList")
    public Object findAllByList(CodeTmplSearchModel searchVo) {
        List<Map> list = codeTmplService.findByList(searchVo);
        return list;
    }

    @ApiOperation("查询详情")
    @GetMapping(value = "/findById/{id}")
    public Map findById(@PathVariable String id) {
        CodeTmplEntity codeTmplEntity = codeTmplService.getById(id);
        if (codeTmplEntity == null) {
            throw ApiException.getInstance("数据不存在，请刷新重试");
        }

        Map result = JSON.parseObject(JSON.toJSONString(codeTmplEntity), Map.class);

        return result;
    }

    @ApiOperation("导入数据")
    @PostMapping(value = "/importData")
    public Object importData(@RequestParam("file") MultipartFile file) throws IOException {
        GzExcelUtil<CodeTmplEntity> excelUtil = new GzExcelUtil<>(CodeTmplEntity.class);
        List<CodeTmplEntity> codeTmplEntityList = excelUtil.importExcel(file.getInputStream());
        if (CollUtil.isEmpty(codeTmplEntityList)) {
            throw ApiException.getInstance("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (CodeTmplEntity importEntity : codeTmplEntityList) {
            try {
                // 验证是否存在这个用户
                CodeTmplEntity uappTmplEntity = codeTmplService.findByTitle(importEntity.getTextPutong());
                if (uappTmplEntity == null) {
                    BeanValidators.validateWithException(uappTmplEntity);
                    codeTmplService.save(importEntity);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、标题 " + importEntity.getTextPutong() + " 导入成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、标题 " + importEntity.getTextPutong() + " 已存在");
                }

            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、标题 " + importEntity.getTextPutong() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw ApiException.getInstance(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @ApiOperation("下载模板")
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        GzExcelUtil util = new GzExcelUtil(CodeTmplEntity.class);
        util.importTemplateExcel(response, "格子模板");
    }

    @ApiOperation("导出数据")
    @PostMapping("/exportData")
    public void exportData(HttpServletResponse response, @RequestBody CodeTmplSearchModel searchVo) {
        List<Map> list = codeTmplService.findByList(searchVo);
        GzExcelUtil<Map> util = new GzExcelUtil(CodeTmplEntity.class);
        util.exportExcel(response, list, "格子模板", searchVo.getExportFieldList());
    }

    @ApiOperation("添加")
    @PostMapping(value = "/add")
    public void add(@Validated @RequestBody CodeTmplAddParamModel paramModel) {
        //方式一：适合单一添加
        CodeTmplEntity codeTmplEntity = new CodeTmplEntity();
        codeTmplEntity.setData(paramModel);
        codeTmplService.save(codeTmplEntity);

        //方法二：适合事务添加
//        appTmplService.add(paramModel);
    }

    @ApiOperation("修改")
    @PostMapping(value = "/edit")
    public void edit(@Validated @RequestBody CodeTmplEditParamModel paramModel) {
        //校验参数
        CodeTmplEntity codeTmplEntity = codeTmplService.getById(paramModel.getId());
        if (codeTmplEntity == null) {
            throw new ApiException("数据不存在，请刷新重试");
        }

        //方式一：适合单一编辑
        codeTmplEntity.setData(paramModel);
        codeTmplService.updateById(codeTmplEntity);

        //方法二：适合事务编辑
//        appTmplService.edit(paramModel);
    }

    @ApiOperation("删除")
    @DeleteMapping(value = "/delByIds/{ids}")
    public void delAllByIds(@PathVariable String[] ids) {
        //适合事务删除
        codeTmplService.dels(ids);
    }
}